package com.surveypark.util;

import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.surveypark.domain.BaseEntity;
import com.surveypark.domain.User;
import com.surveypark.domain.security.Right;
import com.surveypark.struts2.action.BaseAction;
import com.surveypark.struts2.action.UserAware;

public class ValidateUtil {

	/**
	 * ��C�ַ����Ч��
	 * @param str
	 * @return
	 */
	public static boolean isValid(String str){
		if(null == str || "".equals(str.trim())){
			return false;
		}
		return true;
	}
	
	/**
	 * ��֤������Ч��
	 * @param coll
	 * @return
	 */
	public static boolean isValid(Collection<?> coll){
		if(null == coll || coll.isEmpty()){
			return false;
		}
		return true;
	}

	public static boolean isValid(Object[] array) {
		if(null == array || array.length == 0){
			return false;
		}
		return true;
	}

	/**
	 * ��ȡ���е�ʵ��Id�������ַ�
	 */
	public static String extractRoleIds(Collection<? extends BaseEntity> c) {
		if(!ValidateUtil.isValid(c)){
			return null;
		}
		else{
			String temp = "";
			for(BaseEntity e:c){
				temp = temp + e.getId() + ",";
			}
			return temp.substring(0, temp.length() - 1);
		}
	}
	
	/**
	 * 判断是否有权限
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static boolean hasRight(String ns, String actionName, HttpServletRequest req, BaseAction action){
		
		if(!ValidateUtil.isValid(ns) || "/".equals(ns)){
			
			ns = "";
		}
		
		//处理action中携带参数的链接
		if(actionName.contains("?")){
			actionName = actionName.substring(0, actionName.indexOf("?"));
		}
		
		String url = ns + "/" + actionName;
		HttpSession s = req.getSession();
		ServletContext sc = s.getServletContext();
		Map<String, Right> map = (Map<String, Right>)sc.getAttribute("all_rights_map");
		Right r = map.get(url);
		
		if(r == null){
			return false;
		}
		//公共资源
		if(r.isCommon()){
			return true;
		}
		else{
			User user = (User)s.getAttribute("user");
			
			//登陆
			if(user == null){
				return false;
			}
			else{
				//userAware的注入问题
				if(action != null && action instanceof UserAware){
					((UserAware)action).setUser(user);
				}
				
				//超级管理员
				if(user.isSuperAdmin()){
					return true;
				}
				else{
					//有权限
					if(user.hasRight(r)){
						return true;
					}
					else
						return false;
				}
			}		
		}
	}
	
}
